import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import axios from 'axios'

import { I_Response } from '../../types/type'
import { AuthEntity, UserEntity, RoleEntity } from '../../entitys'
import { LoginDto } from './dtos/auth.dto'

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(AuthEntity)
    private readonly authRepository: Repository<AuthEntity>,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @InjectRepository(RoleEntity)
    private readonly roleRepository: Repository<RoleEntity>,
    private readonly jwtService: JwtService
  ) {
    if (process.env.__DEV__) {
      this.caretRole()
    }
  }

  async getUser(body: LoginDto) {
    try {
      return await this.authRepository.findOneBy(body)
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  async caretRole() {
    if ((await this.roleRepository.find()).length >= 2) return
    const role = new RoleEntity()
    role.type = 'nomarl'
    role.permissions = 1
    role.id = 1

    await this.roleRepository.save(role)

    role.id = 2
    role.type = 'admin'
    role.permissions = 1000
    await this.roleRepository.save(role)
    console.log('创建 role =>  ok')
    this.register({ username: 'admin', password: 'admin' }, '1')
  }

  async login(body: LoginDto): Promise<I_Response<unknown>> {
    const user = await this.getUser(body)
    if (user?.id) {
      const token = this.jwtService.sign({
        id: user.id,
        username: user.username,
        time: Date.now()
      })
      return {
        data: { token, id: user.id },
        message: '登录成功'
      }
    }
    return { code: 400, message: '登录失败', success: false }
  }

  async register(
    body: LoginDto,
    id: string = null
  ): Promise<I_Response<unknown>> {
    const user = await this.getUser(body)
    if (user?.id) {
      return { code: 400, message: '账号已存在', success: false }
    }
    try {
      const { data } = await Promise.race([
        axios.get('https://api.shadiao.pro/du'),
        axios.get('https://api.shadiao.pro/chp'),
        axios.get('https://api.shadiao.pro/pyq'),
        axios.get('https://api.shadiao.pro/du')
      ])
      const role = await this.roleRepository.findOneBy({ id: 1 })
      const save = Object.assign(new AuthEntity(), body, {
        [!!id ? 'id' : Symbol.for('id')]: id,
        role
      })
      const login = await this.authRepository.save(save)
      const user = Object.assign(new UserEntity(), {
        id: login.id,
        description: data.data.text,
        login: login
      })
      await this.userRepository.save(user)
      return { data: body, message: '注册成功' }
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
}
